<template>
  <div class="wx-game-page">
    <div class="game-loading d-jcc-aic" v-if="loading">
      <a-spin/>
      <div class="loading-tip">加载中
        <!--        <div class="dot dot-one"></div>-->
        <!--        <div class="dot dot-two"></div>-->
        <!--        <div class="dot dot-three"></div>-->
      </div>
    </div>
    <img class="wx-game-top-bg" src="./assets/bg.jpg">
    <div class="main-wrap">
      <div class="wx-game-page-main">
        <div class="user-nickname">
          <div>{{ gameData.nickname }}，</div>
          <div>欢迎您参加{{ gameData.gameName }}！</div>
        </div>
        <div class="user-game-btn d-aic">
          <div class="user-game-data">
            你已邀请<span class="game-data-num">{{ gameData.finish }}</span>人，
            <span v-if="gameData.target>0">
              还差<span
                class="game-data-num">{{ gameData.target }}</span>人可以领奖
            </span>
            <span v-else>快去领奖吧！</span>
          </div>
          <a-button class="user-share-btn" @click="showPoster=true">我的推广海报</a-button>
        </div>
        <div class="user-share-rank">
          <div class="rank-title">- 推广排行榜 -</div>
          <div
            class="rank-list d-jcs-aic"
            :class="{'active':index%2===0}"
            v-for="(item,index) in rankList"
            :key="index">
            <div class="d-aic flex-grow">
              <div class="rank-index" :class="{'active':index<3}" :key="index">{{ index<3?'TOP'+(index+1):index+1 }}
              </div>
              <div>{{ item.nickname }}</div>
            </div>
            <div class="flex-grow share-num">分享<span class="share-num-content">{{ item.friendCount }}</span>次</div>
          </div>
          <div v-if="!rankList.length" class="rank-empty d-jcc-aic">暂无数据!</div>
        </div>
      </div>
    </div>

    <div class="user-share-poster" v-show="showPoster">
      <div class="poster-content d-jcc-aic">
        <a-icon type="close-circle" class="close-poster" @click="showPoster=false"/>

        <div class="poster-img-wrap d-aic">
          <img class="poster-img" :src="posterCapture"/>
          <div class="poster-tip">长按图片保存至手机或直接发送给好友</div>
        </div>
      </div>
    </div>
    <div class="x-poster-wrap">
      <div class="x-poster">
        <share-poster-preview
          ref="poster"
          v-bind="poster"/>
      </div>
    </div>
    <div class="x-qrCode-wrap">
      <x-qr-code
        ref="qrCode"
        @openQrCode="openQrCode"
        :style="{
          maxWidth: '300px',
          maxHeight: '300px',
        }"/>
    </div>
  </div>
</template>
<script>
  import SharePosterPreview from './share-poster-preview'
  import Canvas2Image from '../perm/utils/canvas2image'
  import API from '../api/h5'
  import XQrCode from '../perm/components/XQrCode'
  // import bg from './assets/bg.jpg'

  export default {
    name: 'GamePage',
    components: { XQrCode, SharePosterPreview },
    data () {
      return {
        showPoster: false,
        loading: true,
        posterCapture: '',
        gameData: {
          nickname: null,
          gameName: null,
          finish: 0,
          target: 0
        },
        poster: {
          qrCode: '',
          avatar: '',
          background: '',
          nickname: ''
        },
        rankList: [{
          nickname: 'XXX',
          friendCount: 999
        }, {
          nickname: 'XXX',
          friendCount: 99
        }, {
          nickname: 'XXX',
          friendCount: 98
        }, {
          nickname: 'XXX',
          friendCount: 97
        }, {
          nickname: 'XXX',
          friendCount: 96
        }]
      }
    },
    computed: {
      id () {
        return this.$route.query.id
      }
    },
    mounted () {
      this.init()
    },
    methods: {
      async init () {
        const posterData = await API.getH5Rank({ gameTaskPlayId: this.id })
        const qrCode = await API.getH5MySharePoster({ gameTaskPlayId: this.id })
          // 后台返回的type是图片就直接赋值否则用草料生成二维码
       if (qrCode.type === 'url') {
           this.$refs.qrCode.generate(qrCode.src)
       } else {
           this.poster.qrCode = qrCode.src
           this.capture()
       }
        const finish = posterData.play.friendCount || 0
        this.rankList = posterData.rankList
        this.gameData = {
          nickname: posterData.play.nickname,
          gameName: posterData.game.name,
          finish: finish,
          target: !posterData.ruleList.length ? 0 : posterData.ruleList[0].target - finish > 0 ? posterData.ruleList[0].target - finish : 0
        }
        try {
          // 加载到model后需要对海报数据进行格式化，同时对尺寸数据进行缩放
          const poster = JSON.parse(posterData.game.posterElements)
          const header = Object.assign({}, {
            ...poster.header
          })

          const nickname = Object.assign({}, {
            ...poster.nickname
          })
          const qrCodeStyle = Object.assign({}, {
            ...poster.qrCode
          })
          this.poster = Object.assign(this.poster, {
            avatarStyle: header,
            nicknameStyle: nickname,
            nickname: posterData.play.nickname,
            qrCodeStyle: qrCodeStyle,
            avatar: posterData.play.headImgUrl,
            background: posterData.game.posterFileUrl
          })
          // this.poster = Object.assign(this.poster, {
          //   avatarStyle: header,
          //   nicknameStyle: nickname,
          //   nickname: posterData.play.nickname,
          //   qrCodeStyle: qrCodeStyle,
          //   avatar: bg,
          //   background: bg
          // })
          console.log(this.poster)
        } catch (e) {
          console.error(e)
        }
        this.loading = false
      },
      openQrCode (image) {
        this.poster.qrCode = image
        console.log(this.poster)
        this.capture()
      },
      capture () {
        const shareContent = this.$refs['poster'].$el // 需要截图的包裹的（原生的）DOM 对象
        if (!shareContent) {
          return
        }
        const width = shareContent.offsetWidth // 获取dom 宽度
        const height = shareContent.offsetHeight // 获取dom 高度
        const canvas = document.createElement('canvas') // 创建一个canvas节点
        const scale = 0.5 // 定义任意放大倍数 支持小数
        canvas.width = width * scale // 定义canvas 宽度 * 缩放
        canvas.height = height * scale // 定义canvas高度 *缩放
        canvas.getContext('2d').scale(scale, scale) // 获取context,设置scale
        const opts = {
          scale: scale, // 添加的scale 参数
          canvas: canvas, // 自定义 canvas
          logging: true, // 日志开关，便于查看html2canvas的内部执行流程
          width: width, // dom 原始宽度
          height: height,
          allowTaint: false,
          useCORS: true // 【重要】开启跨域配置
        }

        const _this = this
        window.html2canvas(shareContent, opts).then(function (canvas) {
          const context = canvas.getContext('2d')
          // 【重要】关闭抗锯齿
          context.mozImageSmoothingEnabled = false
          context.webkitImageSmoothingEnabled = false
          context.msImageSmoothingEnabled = false
          context.imageSmoothingEnabled = false
          // 【重要】默认转化的格式为png,也可设置为其他格式
          _this.posterCapture = Canvas2Image.convertToPNG(canvas, canvas.width, canvas.height).src
          console.log(_this.posterCapture)
        }).catch(e => {
          console.error(e)
        })
      }
    }
  }
</script>

<style scoped lang="less">
  .wx-game-page {
    position: relative;
    width: 100vw;
    min-height: 100vh;

    .wx-game-top-bg {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      /*height: 3.5rem;*/
      /*z-index: 9;*/
    }

    .main-wrap {
      position: relative;
      padding-top: 3rem;
      width: 100%;
    }

    .wx-game-page-main {
      padding: 0 .2rem;
      width: 100%;
      border-radius: .20rem .20rem 0 0;
      background: #F5F5F5;
      z-index: 200;
    }

    .user-nickname {
      padding: .3rem .24rem;
      font-size: .28rem;
      color: #8C8C8C;
    }

    .user-game-btn {
      width: 100%;
      height: 2.22rem;
      border-radius: .12rem;
      flex-direction: column;
      background: white;

      .user-game-data {
        margin: .3rem 0;
        height: 0.44rem;
        font-size: .32rem;
        color: #333333;
      }

      .game-data-num {
        color: #ff5f5f;
      }

      .user-share-btn {
        width: 3.3rem;
        height: .84rem;
        border-radius: .42rem;
        background-color: rgba(24, 144, 255, 100);
        color: rgba(255, 255, 255, 100);
        font-size: .32rem;
        border: none;
        box-shadow: 0 .08rem .12rem 0 rgba(36, 147, 252, 45);
      }
    }

    .user-share-rank {
      margin-top: .24rem;
      padding: 0 .26rem;
      width: 100%;
      border-radius: .12rem;
      background: white;
      box-sizing: border-box;

      .rank-title {
        width: 100%;
        padding: .40rem 0;
        font-size: .32rem;
        font-weight: 600;
        text-align: center;
        color: #333333;
      }

      .rank-list {
        padding: 0 .24rem;
        width: 100%;
        height: .80rem;
        border-radius: .16rem;
        font-size: .28rem;
        color: #595959;
        background-color: rgba(36, 147, 252, .18);

        &.active {
          background-color: #F0F0F0;
        }

        .rank-index {
          margin-right: .50rem;
          width: .80rem;
          text-align: center;

          &.active {
            font-weight: bold;
          }
        }

        .share-num {
          text-align: right;
        }

        .share-num-content {
          margin: 0 0.1rem;
        }
      }

      .rank-list + .rank-list {
        margin-top: .24rem;
      }
    }

    .user-share-poster {
      position: absolute;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background: rgba(0, 0, 0, 0.5);
      z-index: 300;

      .poster-content {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 10.6rem;
        border-radius: .20rem .20rem 0 0;
        font-size: .28rem;
        flex-direction: column;
        background-color: white;
        color: #333333;

        .poster-img {
          width: 4.60rem;
          height: 8.60rem;
          background: slategrey;
        }

        .poster-tip {
          margin-top: .3rem;
          font-size: .36rem;
          color: #8C8C8C;
        }

        .close-poster {
          position: absolute;
          top: .20rem;
          right: .20rem;
          font-size: .56rem;
          color: #9f9f9f;
        }
      }
    }

    .rank-empty {
      height: 3rem;
      color: #9f9f9f;
    }

    .poster-img-wrap {
      flex-direction: column;
    }

    .x-poster-wrap {
      position: fixed;
      left: 18rem;
      top: 18rem;

      .x-poster {
        font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
      }
    }

    .game-loading {
      position: fixed;
      width: 100vw;
      height: 100vh;
      flex-direction: column;
      background: rgba(255, 255, 255, 1);
      z-index: 500;

      .dot {
        display: inline-block;
        width: 0.1rem;
        height: 0.1rem;
        border-radius: 50%;
        background: rgba(0, 0, 0, 0.65);
        background-clip: content-box;
        box-sizing: border-box;
      }

      .dot-one {
        animation: dot 1.5s infinite step-start both;
      }

      .dot-two {
        margin-left: 0.2rem;
        animation: dot 1.5s infinite step-start both;
        animation-delay: 1.5s;
      }

      .dot-three {
        margin-left: 0.2rem;
        animation: dot 1.5s infinite step-start both;
        /*animation-delay: 3s;*/
      }

      @keyframes dot {
        50% {
          background-color: transparent;
        }
      }

      .loading-tip {
        margin-top: 0.3rem;
      }
    }

  }
</style>
